Introduction to Built-in MySQL Functions – Detailed Notes
Course: MySQL Training
Topic: Introduction to Built-in MySQL Functions
Course Link: MySQL Training Course
Demo Link: Register for a Course Demo
1. Introduction to Built-in MySQL Functions
MySQL is a relational database management system used to store, organize, retrieve, and manage structured data. While SQL statements allow users to perform operations on database tables, built-in functions make it easier to process, calculate, transform, and analyze data directly within SQL queries.
Built-in MySQL functions are predefined operations provided by MySQL. They accept zero or more arguments, perform a particular operation, and return a result. Depending on the function, the result may be a number, string, date, time, Boolean-like value, JSON value, or another supported data type.
For example, the UPPER() function converts text to uppercase, ROUND() rounds a numeric value, NOW() returns the current date and time, and COUNT() counts rows or non-NULL values depending on its argument.
SELECT UPPER('mysql');
SELECT ROUND(125.678, 2);
SELECT NOW();
SELECT COUNT(*) FROM employees;
Built-in functions can be used in different parts of SQL statements, including the SELECT, WHERE, ORDER BY, GROUP BY, and HAVING clauses, depending on the function and the query.
2. Learning Objectives
After studying this topic, you should be able to:
- Understand the meaning and purpose of built-in MySQL functions.
- Identify the main categories of MySQL functions.
- Understand function syntax, arguments, return values, and aliases.
- Use string functions to manipulate text.
- Use numeric functions to perform calculations.
- Use date and time functions to work with dates and timestamps.
- Understand aggregate functions for summarizing data.
- Use conditional and NULL-handling functions.
- Combine functions with filtering, sorting, grouping, and joins.
- Recognize common mistakes and write clearer, more reliable queries.
3. What Is a MySQL Function?
A MySQL function is a predefined operation that receives input values, processes them according to its rules, and returns a result. Functions reduce the need to perform common calculations or transformations outside the database.
3.1 General Syntax
SELECT FUNCTION_NAME(argument1, argument2, ...);
In this syntax:
- SELECT: Requests a result from MySQL.
- FUNCTION_NAME: The name of the function to execute.
- Arguments: The values, columns, or expressions supplied to the function.
- Result: The value returned by the function.
Not every function requires arguments. Some functions, such as NOW(), can be called without arguments, while functions such as ROUND() and CONCAT() accept arguments.
3.2 Simple Examples
SELECT LENGTH('Database') AS text_length;
SELECT ABS(-45) AS positive_value;
SELECT CONCAT('My', 'SQL') AS technology;
SELECT CURRENT_DATE() AS today;
The AS keyword assigns a readable label, called a column alias, to a returned value. Aliases are useful when displaying calculated results in reports.
4. Why Are Built-in Functions Important?
Built-in functions help developers and analysts perform data operations within MySQL instead of retrieving raw data and processing every value in an external application.
| Benefit |
Explanation |
Example |
| Data transformation |
Change the format or representation of data. |
UPPER(name) |
| Calculations |
Perform mathematical operations. |
ROUND(price, 2) |
| Date processing |
Extract date parts or calculate date intervals. |
YEAR(order_date) |
| Summarization |
Calculate totals, averages, and counts. |
SUM(amount) |
| Conditional results |
Return different values depending on conditions. |
IF(score >= 50, 'Pass', 'Fail') |
| NULL handling |
Provide alternative results for missing values. |
COALESCE(phone, 'Not provided') |
| Reporting |
Produce formatted and calculated output. |
DATE_FORMAT(order_date, '%Y-%m') |
5. Major Categories of Built-in MySQL Functions
MySQL provides many built-in functions and operators. The following categories cover commonly used functions for everyday SQL development and data analysis. This is an introductory selection, not an exhaustive list of every function available in MySQL.
| Category |
Purpose |
Common Functions |
| String functions |
Manipulate text values. |
CONCAT(), UPPER(), LOWER(), LENGTH(), SUBSTRING(), TRIM() |
| Numeric functions |
Perform mathematical calculations. |
ABS(), ROUND(), CEIL(), FLOOR(), MOD(), SQRT() |
| Date and time functions |
Work with dates, times, and intervals. |
NOW(), CURDATE(), YEAR(), MONTH(), DATEDIFF(), DATE_ADD() |
| Aggregate functions |
Summarize values across rows. |
COUNT(), SUM(), AVG(), MIN(), MAX() |
| Conditional functions |
Return values based on conditions. |
IF(), CASE, NULLIF() |
| NULL-handling functions |
Handle missing or unknown values. |
IFNULL(), COALESCE() |
| Conversion functions |
Convert values between supported types. |
CAST(), CONVERT() |
| JSON functions |
Read and process JSON values. |
JSON_EXTRACT(), JSON_OBJECT(), JSON_ARRAY() |
6. String Functions
String functions operate on text values such as names, email addresses, product descriptions, city names, and codes. They are useful for cleaning data, preparing reports, standardizing text, and extracting parts of strings.
6.1 CONCAT()
The CONCAT() function joins two or more strings into one string. In MySQL, if an argument is NULL, the result of CONCAT() is normally NULL.
SELECT CONCAT('Hello', ' ', 'MySQL') AS message;
-- Result: Hello MySQL
SELECT CONCAT('Amit', ' Sharma') AS full_name;
-- Result: Amit Sharma
Use case: Combining first and last names, constructing labels, or preparing display text.
6.2 UPPER() and LOWER()
UPPER() converts text to uppercase, while LOWER() converts text to lowercase.
SELECT UPPER('mysql functions') AS uppercase_text;
-- Result: MYSQL FUNCTIONS
SELECT LOWER('DATABASE TRAINING') AS lowercase_text;
-- Result: database training
These functions can help standardize the display of text. Case sensitivity in comparisons depends on the character set and collation used by the expression or column.
6.3 LENGTH() and CHAR_LENGTH()
LENGTH() returns the length of a string in bytes, whereas CHAR_LENGTH() returns the number of characters. The results may differ when a character uses multiple bytes in the selected character set.
SELECT LENGTH('MySQL') AS byte_length;
SELECT CHAR_LENGTH('MySQL') AS character_count;
For ordinary ASCII text, the results are usually the same. For multibyte characters, use CHAR_LENGTH() when the goal is to count characters rather than bytes.
6.4 SUBSTRING()
SUBSTRING() extracts part of a string. MySQL string positions begin at 1.
SELECT SUBSTRING('Database', 1, 4) AS extracted_text;
-- Result: Data
SELECT SUBSTRING('Database', 5) AS remaining_text;
-- Result: base
In the first example, MySQL begins at character 1 and returns four characters. In the second, it returns the string from character 5 to the end.
6.5 TRIM()
TRIM() removes leading and trailing spaces by default. It is often useful when cleaning user-entered values.
SELECT TRIM(' MySQL ') AS cleaned_text;
-- Result: MySQL
Related functions include LTRIM(), which removes leading spaces, and RTRIM(), which removes trailing spaces.
6.6 REPLACE()
REPLACE() replaces occurrences of a specified substring with another string.
SELECT REPLACE('Learn SQL Basics', 'Basics', 'Functions') AS updated_text;
-- Result: Learn SQL Functions
This function can help transform text in query results. It does not permanently change table data unless used as part of an appropriate data-modification statement.
6.7 Combining String Functions
SELECT
UPPER(TRIM(' mysql training ')) AS formatted_text,
CHAR_LENGTH(TRIM(' mysql training ')) AS text_length;
Multiple functions can be nested. MySQL evaluates the inner expression and passes its result to the outer function.
7. Numeric Functions
Numeric functions perform calculations on integers, decimal values, and other supported numeric expressions. They are commonly used for prices, salaries, discounts, quantities, measurements, and statistical analysis.
7.1 ABS()
ABS() returns the absolute value of a number, removing its negative sign when the input is negative.
SELECT ABS(-125) AS absolute_value;
-- Result: 125
7.2 ROUND()
ROUND() rounds a number to a specified number of decimal places.
SELECT ROUND(123.4567, 2) AS rounded_value;
-- Result: 123.46
SELECT ROUND(78.4) AS rounded_integer;
-- Result: 78
Use rounding for display or business calculations when the required rounding rule is understood. Financial systems should define their precision and rounding requirements carefully.
7.3 CEIL() and FLOOR()
CEIL() or CEILING() returns the smallest integer greater than or equal to the argument. FLOOR() returns the largest integer less than or equal to the argument.
SELECT CEIL(12.2) AS ceiling_value;
-- Result: 13
SELECT FLOOR(12.8) AS floor_value;
-- Result: 12
7.4 MOD()
MOD() returns the remainder after division.
SELECT MOD(17, 5) AS remainder;
-- Result: 2
It can be used for tasks such as identifying even numbers, dividing items into groups, or checking periodic patterns.
SELECT 18 % 2 AS even_number_check;
-- Result: 0
7.5 SQRT() and POWER()
SQRT() returns a square root, while POWER() raises a number to a specified power.
SELECT SQRT(81) AS square_root;
-- Result: 9
SELECT POWER(3, 4) AS exponent_result;
-- Result: 81
Check input ranges and data types when using mathematical functions. For example, a negative value supplied to SQRT() does not produce an ordinary real-number square root.
8. Date and Time Functions
Date and time functions work with date, time, datetime, and timestamp values. They are essential for order tracking, employee records, booking systems, subscriptions, billing, and time-based reports.
8.1 NOW(), CURDATE(), and CURTIME()
NOW() returns the current date and time, CURDATE() returns the current date, and CURTIME() returns the current time. Results depend on the MySQL session's time-zone context where applicable.
SELECT NOW() AS current_datetime;
SELECT CURDATE() AS current_date;
SELECT CURTIME() AS current_time;
8.2 YEAR(), MONTH(), and DAY()
These functions extract individual date components from a date or datetime expression.
SELECT YEAR('2026-10-16') AS order_year;
-- Result: 2026
SELECT MONTH('2026-10-16') AS order_month;
-- Result: 10
SELECT DAY('2026-10-16') AS order_day;
-- Result: 16
8.3 DATEDIFF()
DATEDIFF() returns the number of days between two date expressions. It uses the date portions and ignores the time portions.
SELECT DATEDIFF('2026-10-16', '2026-10-01') AS days_difference;
-- Result: 15
The result is based on the first date minus the second date. Reversing the arguments can produce a negative result.
8.4 DATE_ADD() and DATE_SUB()
DATE_ADD() adds an interval to a date, while DATE_SUB() subtracts an interval.
SELECT DATE_ADD('2026-10-16', INTERVAL 7 DAY) AS next_week;
-- Result: 2026-10-23
SELECT DATE_SUB('2026-10-16', INTERVAL 1 MONTH) AS previous_month;
Intervals can use supported units such as days, months, years, hours, and minutes. Month arithmetic follows MySQL's date rules, so results near the end of a month should be tested for the intended business behavior.
8.5 DATE_FORMAT()
DATE_FORMAT() formats a date or datetime as a string using format specifiers.
SELECT DATE_FORMAT('2026-10-16', '%d-%m-%Y') AS formatted_date;
-- Result: 16-10-2026
SELECT DATE_FORMAT(NOW(), '%Y-%m') AS year_month;
| Specifier |
Meaning |
Example |
%Y |
Four-digit year |
2026 |
%m |
Two-digit month |
10 |
%d |
Two-digit day of month |
16 |
%H |
Hour in 24-hour format |
14 |
%i |
Minutes |
35 |
%s |
Seconds |
09 |
Important: %i represents minutes in MySQL date formatting; it should not be confused with the month specifier %m.
9. Aggregate Functions
Aggregate functions calculate a single summary result from a set of rows. They are frequently used with GROUP BY to calculate results for categories such as departments, products, customers, and months.
9.1 COUNT()
COUNT(*) counts rows. COUNT(column_name) counts non-NULL values in the specified column.
SELECT COUNT(*) AS total_employees
FROM employees;
SELECT COUNT(department_id) AS employees_with_department
FROM employees;
9.2 SUM()
SUM() calculates the total of non-NULL values in a numeric expression.
SELECT SUM(salary) AS total_salary
FROM employees;
9.3 AVG()
AVG() calculates the average of non-NULL numeric values.
SELECT AVG(salary) AS average_salary
FROM employees;
9.4 MIN() and MAX()
MIN() returns the minimum value, while MAX() returns the maximum value within the selected group of rows.
SELECT
MIN(salary) AS lowest_salary,
MAX(salary) AS highest_salary
FROM employees;
9.5 Aggregate Functions with GROUP BY
The following example calculates employee counts and average salaries for each department.
SELECT
department_id,
COUNT(*) AS employee_count,
AVG(salary) AS average_salary,
MAX(salary) AS highest_salary
FROM employees
GROUP BY department_id;
GROUP BY divides rows into groups. The aggregate functions then calculate a result for each group. Conditions on aggregated results are generally placed in HAVING, while conditions that filter individual rows are generally placed in WHERE.
10. Conditional Functions
Conditional functions allow queries to produce different results depending on whether specified conditions are satisfied.
10.1 IF()
IF(condition, value_if_true, value_if_false) returns one value when the condition is true and another when it is false or not true.
SELECT IF(75 >= 50, 'Pass', 'Fail') AS exam_result;
-- Result: Pass
Example using a table:
SELECT
employee_name,
salary,
IF(salary >= 50000, 'High Salary', 'Standard Salary') AS salary_category
FROM employees;
10.2 CASE
CASE is a SQL conditional expression that supports multiple conditions. It is suitable when several categories must be assigned.
SELECT
employee_name,
salary,
CASE
WHEN salary >= 80000 THEN 'Senior Pay'
WHEN salary >= 50000 THEN 'Mid Pay'
WHEN salary >= 30000 THEN 'Entry Pay'
ELSE 'Below Entry Range'
END AS salary_band
FROM employees;
MySQL evaluates the conditions in order and returns the result for the first matching condition. The ELSE branch handles values that do not match any listed condition. If no condition matches and no ELSE is supplied, the result is NULL.
10.3 NULLIF()
NULLIF(expression1, expression2) returns NULL when both expressions are equal; otherwise, it returns the first expression.
SELECT NULLIF(10, 10) AS comparison_result;
-- Result: NULL
SELECT NULLIF(10, 5) AS comparison_result;
-- Result: 10
This function can be useful for avoiding a zero denominator in a division expression.
SELECT revenue / NULLIF(quantity, 0) AS revenue_per_item
FROM sales;
If quantity is zero, the denominator becomes NULL, so the division result is NULL rather than a division-by-zero calculation.
11. NULL-handling Functions
In MySQL, NULL represents a missing or unknown value. It is not the same as zero, an empty string, or the text value 'NULL'. NULL-handling functions allow queries to provide fallback values or choose among possible values.
11.1 IFNULL()
IFNULL(expression, alternative) returns the expression when it is not NULL; otherwise, it returns the alternative.
SELECT IFNULL(NULL, 'Not Available') AS contact_status;
-- Result: Not Available
SELECT IFNULL(0, 100) AS amount;
-- Result: 0
The second example returns zero because zero is not NULL.
11.2 COALESCE()
COALESCE() returns the first non-NULL expression from its argument list.
SELECT COALESCE(NULL, NULL, 'MySQL', 'SQL') AS selected_value;
-- Result: MySQL
Example with employee contact details:
SELECT
employee_name,
COALESCE(work_phone, personal_phone, 'No phone provided') AS contact_number
FROM employees;
MySQL checks the supplied expressions from left to right and returns the first non-NULL value. Make sure the possible return values have compatible data types.
11.3 Testing for NULL
Use IS NULL or IS NOT NULL to test for NULL values. Do not use = NULL for ordinary NULL checks.
SELECT *
FROM employees
WHERE phone_number IS NULL;
SELECT *
FROM employees
WHERE phone_number IS NOT NULL;
12. Type Conversion Functions
Type conversion functions change how a value is represented or interpreted. They are useful when data comes from different sources or needs a specific type for calculation or comparison.
12.1 CAST()
CAST() converts an expression to a specified supported data type.
SELECT CAST('125' AS UNSIGNED) AS numeric_value;
-- Result: 125
SELECT CAST('2026-10-16' AS DATE) AS converted_date;
12.2 CONVERT()
CONVERT() can also convert an expression to a specified type.
SELECT CONVERT('250' , UNSIGNED) AS numeric_value;
SELECT CONVERT('2026-10-16', DATE) AS converted_date;
Invalid or unsuitable input may produce warnings, errors, or conversion results affected by the current SQL mode. Validate input rather than assuming every text value converts successfully.
13. Combining Built-in Functions with SELECT
Functions are often used inside a SELECT statement to create calculated columns, clean text, extract dates, and summarize values.
13.1 Creating Calculated Columns
SELECT
product_name,
price,
ROUND(price * 1.18, 2) AS price_with_tax
FROM products;
This example calculates a value by multiplying the price by 1.18 and rounding the result to two decimal places. It illustrates a calculation only; actual tax treatment depends on the applicable business rules.
13.2 Using Functions in WHERE
SELECT employee_name, salary
FROM employees
WHERE ROUND(salary, 0) > 50000;
Functions can appear in the WHERE clause. However, applying a function to an indexed column can prevent an ordinary index range lookup from being used in some cases. When possible, compare the original column to an appropriate range instead.
13.3 Using Functions in ORDER BY
SELECT employee_name, salary
FROM employees
ORDER BY ROUND(salary, 0) DESC;
This sorts the returned rows using the rounded salary expression, from highest to lowest.
13.4 Using Functions with GROUP BY
SELECT
YEAR(order_date) AS order_year,
COUNT(*) AS total_orders
FROM orders
GROUP BY YEAR(order_date)
ORDER BY order_year;
This query groups orders by year and counts the number of orders in each group.
14. Practical Example Using an Employees Table
Consider an employees table containing the following columns:
| Column |
Possible Data Type |
Description |
employee_id |
INT |
Unique employee identifier |
employee_name |
VARCHAR(100) |
Employee's name |
department_id |
INT |
Department identifier |
salary |
DECIMAL(10,2) |
Employee salary |
joining_date |
DATE |
Employee joining date |
phone_number |
VARCHAR(20) |
Contact number |
The following queries demonstrate how built-in functions can be applied to this table.
14.1 Standardize Employee Names
SELECT
employee_name,
UPPER(TRIM(employee_name)) AS standardized_name
FROM employees;
14.2 Calculate Annual Salary
SELECT
employee_name,
salary,
salary * 12 AS annual_salary
FROM employees;
This calculation assumes the salary column stores a monthly salary. Adjust the calculation if the column represents a different pay period.
14.3 Find Employee Tenure in Days
SELECT
employee_name,
joining_date,
DATEDIFF(CURDATE(), joining_date) AS days_employed
FROM employees;
The calculation returns a day difference between the current date and the joining date. It does not automatically account for business-specific definitions of completed service or employment periods.
14.4 Categorize Salaries
SELECT
employee_name,
salary,
CASE
WHEN salary >= 80000 THEN 'High'
WHEN salary >= 50000 THEN 'Medium'
ELSE 'Standard'
END AS salary_category
FROM employees;
14.5 Summarize Salaries by Department
SELECT
department_id,
COUNT(*) AS employee_count,
ROUND(AVG(salary), 2) AS average_salary,
SUM(salary) AS total_monthly_salary
FROM employees
GROUP BY department_id
ORDER BY total_monthly_salary DESC;
15. Built-in Functions and NULL Values
NULL handling is an important part of using MySQL functions correctly. Many functions return NULL when one or more relevant arguments are NULL, although the exact behavior depends on the specific function.
| Expression |
Typical Result |
Reason |
CONCAT('A', NULL) |
NULL |
CONCAT() returns NULL if an argument is NULL. |
IFNULL(NULL, 'N/A') |
N/A |
Uses the alternative value. |
COALESCE(NULL, 5, 10) |
5 |
Returns the first non-NULL value. |
NULL + 10 |
NULL |
Arithmetic involving NULL generally produces NULL. |
COUNT(*) |
Number of rows |
Counts rows regardless of NULL values in individual columns. |
COUNT(phone_number) |
Number of non-NULL phone values |
Does not count NULL entries in that column. |
When building reports, decide how missing values should be represented. Replacing NULL with zero may be appropriate in some calculations but misleading in others, such as missing salary or missing customer contact information.
16. Scalar Functions vs Aggregate Functions
MySQL functions can be understood by how they process data. Two important groups are scalar functions and aggregate functions.
| Feature |
Scalar Function |
Aggregate Function |
| Input |
Usually processes an expression for each row or a supplied value. |
Processes a set of rows or values. |
| Typical output |
A result for each evaluated row, or one result for a supplied expression. |
A summary value for a group or the entire selected set. |
| Examples |
UPPER(), ABS(), YEAR() |
COUNT(), SUM(), AVG() |
| Common use |
Formatting, transformation, calculations. |
Summaries and reports. |
For example, UPPER(employee_name) can produce an uppercase name for each employee row. In contrast, COUNT(*) can return a single count for all selected employee rows or a separate count for each group when used with GROUP BY.
17. Common Mistakes When Using MySQL Functions
| Mistake |
Incorrect or Risky Approach |
Better Approach |
| Using incorrect NULL comparison |
WHERE phone_number = NULL |
WHERE phone_number IS NULL |
| Confusing bytes and characters |
Using LENGTH() when character count is required. |
Use CHAR_LENGTH() for character count. |
| Ignoring NULL arguments |
Assuming CONCAT() will skip NULL values. |
Use CONCAT_WS() or handle NULL values explicitly when suitable. |
| Using aggregate functions incorrectly |
Selecting unrelated columns with aggregate results without appropriate grouping. |
Use suitable GROUP BY expressions and understand MySQL's grouping rules. |
| Formatting dates incorrectly |
Confusing %m and %i. |
Remember %m is month and %i is minutes. |
| Assuming conversion always succeeds |
Casting arbitrary text to numeric values without validation. |
Validate input and inspect warnings or errors. |
| Reducing index usefulness |
Applying a function to an indexed column in a filter unnecessarily. |
Prefer a direct range predicate where equivalent and appropriate. |
| Misusing aliases |
Assuming a SELECT alias is available in every clause. |
Follow MySQL's name-resolution rules; use the expression or a derived query when needed. |
18. Performance and Best Practices
- Choose the right function: Use the function that matches the data type and intended operation.
- Use meaningful aliases: Give calculated columns names that explain their purpose.
- Handle NULL values deliberately: Decide whether missing values should remain NULL or be replaced with a fallback.
- Be careful with data conversion: Ensure converted values are valid and compatible with the destination type.
- Understand date and time zones: Confirm the time-zone requirements when working with current timestamps and stored time values.
- Avoid unnecessary repeated calculations: Reusing expressions through a derived table or common table expression can improve readability, though the optimizer determines execution behavior.
- Keep predicates index-friendly: Avoid wrapping indexed columns in functions in filters when an equivalent direct comparison is possible.
- Check query plans: Use
EXPLAIN to inspect how MySQL plans to execute important queries.
- Test edge cases: Include NULL values, empty strings, negative numbers, unusual dates, and boundary values in testing.
- Use the correct precision: For currency and other exact decimal calculations, choose suitable decimal types and business-approved rounding rules.
19. Mini Project: Employee Data Analysis Using Built-in Functions
Project objective: Use built-in MySQL functions to prepare a simple employee analysis report.
19.1 Requirements
- Display employee names in uppercase after removing leading and trailing spaces.
- Calculate estimated annual salary from monthly salary.
- Show employee tenure in days.
- Replace missing phone numbers with a readable message.
- Classify employees into salary bands.
- Calculate employee counts and average salaries by department.
19.2 Example Query
SELECT
employee_id,
UPPER(TRIM(employee_name)) AS employee_name,
salary AS monthly_salary,
ROUND(salary * 12, 2) AS annual_salary,
DATEDIFF(CURDATE(), joining_date) AS tenure_days,
COALESCE(phone_number, 'Not provided') AS contact_number,
CASE
WHEN salary >= 80000 THEN 'High'
WHEN salary >= 50000 THEN 'Medium'
ELSE 'Standard'
END AS salary_band
FROM employees
ORDER BY annual_salary DESC;
19.3 Department Summary Query
SELECT
department_id,
COUNT(*) AS employee_count,
ROUND(AVG(salary), 2) AS average_monthly_salary,
SUM(salary) AS total_monthly_salary,
MAX(salary) AS highest_monthly_salary,
MIN(salary) AS lowest_monthly_salary
FROM employees
GROUP BY department_id
ORDER BY average_monthly_salary DESC;
19.4 Expected Learning Outcomes
By completing this project, learners practice text transformation, mathematical calculations, date processing, NULL handling, conditional logic, aggregation, grouping, and sorting in a realistic database task.
20. Practice Exercises
- Write a query to display the word
mysql in uppercase.
- Write a query to join the strings
SQL and Training with a space between them.
- Write a query to round
456.789 to two decimal places.
- Write a query to find the current date and time.
- Write a query to extract the year from
2026-10-16.
- Write a query to calculate the difference in days between
2026-10-16 and 2026-10-01.
- Write a query to count all rows in the
employees table.
- Write a query to calculate the average salary from the
employees table.
- Write a query that displays
Not Provided when a phone number is NULL.
- Write a query to classify salaries of 50000 or more as
Eligible and other salaries as Review.
21. Practice Exercise Solutions
Solution 1: Uppercase Text
SELECT UPPER('mysql') AS result;
Solution 2: Join Strings
SELECT CONCAT('SQL', ' ', 'Training') AS result;
Solution 3: Round a Number
SELECT ROUND(456.789, 2) AS result;
Solution 4: Current Date and Time
SELECT NOW() AS current_datetime;
Solution 5: Extract the Year
SELECT YEAR('2026-10-16') AS result;
Solution 6: Difference in Days
SELECT DATEDIFF('2026-10-16', '2026-10-01') AS result;
Solution 7: Count Rows
SELECT COUNT(*) AS total_employees
FROM employees;
Solution 8: Average Salary
SELECT AVG(salary) AS average_salary
FROM employees;
Solution 9: Replace NULL Phone Numbers
SELECT
employee_name,
COALESCE(phone_number, 'Not Provided') AS contact_number
FROM employees;
Solution 10: Salary Classification
SELECT
employee_name,
salary,
CASE
WHEN salary >= 50000 THEN 'Eligible'
ELSE 'Review'
END AS eligibility_status
FROM employees;
22. Interview Questions and Answers
Q1. What are built-in MySQL functions?
Built-in MySQL functions are predefined operations that accept values or expressions, perform specific tasks, and return results. Examples include UPPER(), ROUND(), NOW(), and COUNT().
Q2. What are the main categories of MySQL functions?
Common categories include string, numeric, date and time, aggregate, conditional, NULL-handling, type conversion, and JSON functions.
Q3. What is the difference between LENGTH() and CHAR_LENGTH()?
LENGTH() returns a string's byte length, whereas CHAR_LENGTH() returns its character count. These can differ for multibyte character sets.
Q4. What is the difference between UPPER() and LOWER()?
UPPER() converts text to uppercase, while LOWER() converts text to lowercase.
Q5. What is the difference between ROUND(), CEIL(), and FLOOR()?
ROUND() rounds to a specified precision, CEIL() returns the smallest integer not less than the value, and FLOOR() returns the largest integer not greater than the value.
Q6. What is the difference between NOW() and CURDATE()?
NOW() returns the current date and time, whereas CURDATE() returns only the current date.
Q7. What is the difference between COUNT(*) and COUNT(column_name)?
COUNT(*) counts rows, while COUNT(column_name) counts only rows where the specified expression is not NULL.
Q8. What is the difference between WHERE and HAVING when using aggregate functions?
WHERE filters rows before grouping. HAVING filters groups after aggregate calculations have been performed.
Q9. What is the difference between IFNULL() and COALESCE()?
IFNULL() accepts two expressions and returns the second when the first is NULL. COALESCE() accepts multiple expressions and returns the first non-NULL value.
Q10. What is the purpose of CASE?
CASE evaluates conditions and returns a result for the first matching branch. It is useful for assigning categories and producing conditional output.
Q11. What does CAST() do?
CAST() converts an expression to a specified supported data type, such as converting text containing a valid number to a numeric type.
Q12. Can built-in functions be used in WHERE?
Yes. Functions can be used in WHERE conditions, but applying a function to an indexed column may affect index usage. When possible, use an equivalent direct range condition.
Q13. Do all MySQL functions return a value of the same data type as their input?
No. The return type depends on the function. For example, YEAR() returns a numeric year component, CONCAT() returns a string, and aggregate functions return results according to their documented behavior and input types.
Q14. What happens when NULL is passed to a function?
The behavior depends on the function. Many expressions return NULL when an argument is NULL, while functions such as IFNULL() and COALESCE() specifically handle NULL values.
Q15. How can you learn about an unfamiliar MySQL function?
Consult the official MySQL Reference Manual, verify the function's argument types and return behavior, and test representative values including NULL and boundary cases.
23. Quick Revision Notes
- String functions:
CONCAT(), UPPER(), LOWER(), LENGTH(), CHAR_LENGTH(), SUBSTRING(), TRIM(), REPLACE().
- Numeric functions:
ABS(), ROUND(), CEIL(), FLOOR(), MOD(), SQRT(), POWER().
- Date and time functions:
NOW(), CURDATE(), CURTIME(), YEAR(), MONTH(), DAY(), DATEDIFF(), DATE_ADD(), DATE_SUB(), DATE_FORMAT().
- Aggregate functions:
COUNT(), SUM(), AVG(), MIN(), MAX().
- Conditional logic:
IF() and CASE.
- NULL handling:
IFNULL(), COALESCE(), and NULLIF().
- Type conversion:
CAST() and CONVERT().
- Use
IS NULL to test for NULL values.
- Use
GROUP BY to calculate aggregates for groups and HAVING to filter groups.
- Use aliases to make calculated output easier to read.
- Check official documentation for exact behavior, supported arguments, and version-specific details.
24. Official Documentation and Further Learning
25. Conclusion
Built-in MySQL functions are essential tools for retrieving, transforming, calculating, and analyzing database information. String functions help standardize text, numeric functions perform calculations, date and time functions support time-based analysis, aggregate functions summarize records, and conditional or NULL-handling functions help manage different data situations.
To become confident with MySQL functions, practice them using real tables, combine them with SELECT, WHERE, GROUP BY, HAVING, and ORDER BY, and test how they behave with NULL values and unusual inputs. For further study, visit the MySQL Training Course or register for a course demo.